﻿using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using Battle.View;
using ProtoBuf.Message;

namespace Battle
{
    public class BattlePanel : MonoBehaviour
    {
        public List<UIAtlas> useAtlas;

        public List<BattleHeroItem> heroItems;
        public GameObject heroItemPref;
        public Transform heroAnthor;
        public SmoothBar angerBar;
        public UILabel roundNumber;
        public ComboKit comboKit;
        public BattleResultPanel resultPanel;
        public TransferFormationPanel transferPanel;
        public RoundEffectKit roundEffect;
        public GameObject notTurnMask;

        public GameObject topObj;
        public GameObject bottomObj;


        public BattleViewCtrl viewCtrl;
        public GameObject transBtn;
        //public GameObject disTransBtn;//不可换阵按钮
        public EnemyHeroInfo enemyInfo;
        public EnemyHeroInfo enemyInfoMonster;

        public Transform wordAnchor;
        public Transform buffAnchor;
        public UICooldownKit cooldownKit;

        public TweenPosition roundAniPos;
        public GameObject roundObj;


        //public TweenPosition changeBtnTweenPos;
        public TweenAlpha changeBtnTweenAlpha;

        //public TweenPosition angerBarTween;
        public TweenAlpha angerBarTween;

        public TweenAlpha bottomObjTween;


        public GameObject angerEffect1;
        public GameObject angerEffect2;
        public GameObject angerEffect3;
        public GameObject angerMark1;
        public GameObject angerMark2;
        public GameObject angerMark3;

        public UILabel autoTimeLabel;
        public UICooldownKit autoTimeLeft;

        public BattleUltimateCoverPanel ultimateCoverPanel;

        public GuidePanel guidePanel;

        public GameObject skipButton;

        public GameObject speedButton;

        public GameObject autoSkipUltiButton;

        public GameObject skilUltimateTip;

        public void ShowAutoCountDownLabel(float num)
        {
            autoTimeLeft.Show(num);
        }
        public void HideAutoCountDownLabel()
        {
            autoTimeLeft.Hide();
        }


        public void Init(BattleViewCtrl viewCtrl)
        {
            this.viewCtrl = viewCtrl;
            roundEffect.Hide();
            comboKit.Hide();
            resultPanel.Hide();
            transferPanel.Hide();

            gameObject.SetActive(true);
            foreach (var heroItem in heroItems)
            {
                Destroy(heroItem.gameObject);
            }
            heroItems.Clear();

            var ids = viewCtrl.GetActorUids(BattleCamp.Attacker);
            List<BattleCharacter> bcs = new List<BattleCharacter>();
            for (int i = 0; i < ids.Count; ++i)
            {
                bcs.Add(viewCtrl.GetBattleCharacter(ids[i]));
            }
            bcs.Sort(delegate (BattleCharacter a, BattleCharacter b) { return a.FPId - b.FPId; });
            float widthX = 175f;
            float firstX = -(bcs.Count - 1) * widthX;
            for (int i = 0; i < bcs.Count; ++i)
            {
                if (i >= 4)
                {
                    break;
                }
                var bc = bcs[i];
                GameObject obj = GameObject.Instantiate(heroItemPref) as GameObject;
                obj.transform.SetParent(heroAnthor);
                obj.transform.localScale = Vector3.one;
                obj.transform.localEulerAngles = Vector3.zero;
                obj.transform.localPosition = new Vector3(firstX + i * widthX, 0, 0);
                BattleHeroItem bhi = obj.GetComponent<BattleHeroItem>();
                bhi.Init(bc, this);
                heroItems.Add(bhi);
            }
            angerBar.Init(viewCtrl.GetAngerNum(BattleCamp.Attacker), viewCtrl.GetAngerMax(BattleCamp.Attacker));


            // 换阵按钮
            if (viewCtrl.IsCanTransfer())
            {
                ShowChangeBtn();
            }
            else
            {
                HideChangeBtn();
            }
            // 怒气条
            AngerBarAni();
            // 英雄按钮
            HeroActorAni();
            // 回合数
            RoundAni();
            HideEnemyInfo();

            if (BattleViewCtrl.GetInstance().isAuto)
            {
                EnterAuto();
            }
            else
            {
                LeaveAuto();
            }

            if (StaticData.curBattleData.battleType == BattleType.FIRST)
            {
                HideSkipButton();
            }
            else
            {
                ShowSkipButton();
            }

            autoSkipUltiButton.GetComponent<SkipUltiBtn>().Refresh();
        }

        public void HideSkipButton()
        {
            skipButton.SetActive(false);
        }
        public void ShowSkipButton()
        {
            skipButton.SetActive(true);
        }

        /// <summary>
        /// 怒气条动画
        /// </summary>
        public void AngerBarAni()
        {
            angerBarTween.ResetToBeginning();
            angerBarTween.PlayForward();
            angerBar.gameObject.SetActive(true);
        }

        public void HideAngerBar()
        {
            angerBar.gameObject.SetActive(false);
        }

        /// <summary>
        /// 回合数动画
        /// </summary>
        public void RoundAni()
        {
            roundAniPos.ResetToBeginning();
            roundAniPos.PlayForward();
            roundObj.SetActive(true);
        }

        /// <summary>
        /// 人物按钮动画
        /// </summary>
        public void HeroActorAni()
        {
            bottomObjTween.ResetToBeginning();
            bottomObjTween.PlayForward();
            bottomObj.SetActive(true);
        }

        /// <summary>
        /// 换阵按钮动画
        /// </summary>
        public void ShowChangeBtn()
        {
            transBtn.SetActive(true);
            //changeBtnTweenPos.ResetToBeginning();
            //changeBtnTweenPos.PlayForward();
            changeBtnTweenAlpha.ResetToBeginning();
            changeBtnTweenAlpha.PlayReverse();
        }
        public void HideChangeBtn()
        {
            changeBtnTweenAlpha.ResetToBeginning();
            changeBtnTweenAlpha.PlayForward();
            StartCoroutine(_HideChangeBtn(changeBtnTweenAlpha.duration));
        }
        IEnumerator _HideChangeBtn(float duration)
        {
            yield return new WaitForSeconds(duration);
            transBtn.SetActive(false);
        }


        public void Hide()
        {
            gameObject.SetActive(false);
            resultPanel.Hide();
            foreach (var obj in uiParticleTrans)
            {
                Destroy(obj);
            }
            uiParticleTrans.Clear();
            foreach (var atlas in useAtlas)
            {
                Resources.UnloadAsset(atlas.spriteMaterial.mainTexture);
            }
        }

        public void EnterOurTurn()
        {
            //先还原物件
            roundNumber.text = viewCtrl.GetRoundNum() + "/" + viewCtrl.maxRoundNum;
            foreach (var item in heroItems)
            {
                item.TurnEnter();
            }
            if (viewCtrl.IsCanTransfer())
            {
                ShowChangeBtn();
            }
            else
            {
                HideChangeBtn();
            }
            //transBtn.SetActive(!viewCtrl.hasRoundFight);
            notTurnMask.SetActive(false);


            topObj.SetActive(true);
            bottomObj.SetActive(true);

            if (BattleViewCtrl.GetInstance().isAuto)
            {
                EnterAuto();
            }
            else
            {
                LeaveAuto();
            }
        }

        public void LeaveOutTurn()
        {
            roundNumber.text = viewCtrl.GetRoundNum() + "/" + viewCtrl.maxRoundNum;
            foreach (var item in heroItems)
            {
                item.TurnOver();
            }
            HideEnemyInfo();
            HideCooldown();
            HideAutoCountDownLabel();
            notTurnMask.SetActive(true);
        }

        public void ShowEnemyInfo(BattleCharacter ch)
        {
            if (!string.IsNullOrEmpty(ch.iconName))
            {
                enemyInfo.SetCharactor(ch);
                enemyInfoMonster.Hide();
            }
            else
            {
                enemyInfo.Hide();
                enemyInfoMonster.SetCharactor(ch);
            }
        }
        public void ShowEnemyInfoDead(BattleCharacter ch)
        {
            if (!string.IsNullOrEmpty(ch.iconName))
            {
                enemyInfo.Dead(ch);
                enemyInfoMonster.Hide();
            }
            else
            {
                enemyInfo.Hide();
                enemyInfoMonster.Dead(ch);
            }
        }
        public void HideEnemyInfo()
        {
            enemyInfo.Hide();
            enemyInfoMonster.Hide();
        }

        public void UltimateHide()
        {
            HideEnemyInfo();
            topObj.SetActive(false);
            bottomObj.SetActive(false);
            enemyInfo.Hide();
            enemyInfoMonster.Hide();
            guidePanel.GetComponent<GuideTipPanel>().Hide();
            if (GetComponent<BattleHeroItemGudieCtrl>() != null)
            {
                GetComponent<BattleHeroItemGudieCtrl>().EnterUltimate();
            }
        }

        public void ShowUltimateSkipTip()
        {
            skilUltimateTip.SetActive(true);
        }

        public void HideUltimateSkipTip()
        {
            skilUltimateTip.SetActive(false);
        }

        public void ShowUltimateCoverPanel()
        {
            ultimateCoverPanel.Show();
        }
        public void HideUltimateCoverPanel()
        {
            ultimateCoverPanel.Hide();
        }

        public void UltimateOver()
        {
            topObj.SetActive(true);
            //bottomObj.SetActive(true);

            HeroActorAni();
            AngerBarAni();
            HideUltimateCoverPanel();

            if (GetComponent<BattleHeroItemGudieCtrl>() != null)
            {
                GetComponent<BattleHeroItemGudieCtrl>().LeaveUltimate();
            }
        }

        public void ShowResult()
        {
            guidePanel.Hide();
            foreach (var item in heroItems)
            {
                Destroy(item.gameObject);
            }
            heroItems.Clear();

            topObj.SetActive(false);
            bottomObj.SetActive(false);

            roundEffect.Hide();
            comboKit.Hide();
            transferPanel.Hide();
            LeaveAuto();

            if (StaticData.curBattleData.isPlayBack)
            {
                BattleNetOver.PlaybackOver();
            }
            else
            {
                BattleNetOver.BattleOver(StaticData.curBattleData.battleType);
            }
        }

        public void ShowResultConfirm(bool result)
        {
            if (StaticData.curBattleData.battleType == BattleType.RUSH)
            {
                resultPanel.ShowResult(BattleResultPanel.ResultPanelType.Unknown);
            }
            else
            {
                if (result)
                {
                    resultPanel.ShowResult(BattleResultPanel.ResultPanelType.Win);
                    if (StaticData.curBattleData.battleType == BattleType.PVE)
                    {
                        BattleManager.Instance.ShowCopyStoneBalance();
                    }
                }
                else
                {
                    resultPanel.ShowResult(BattleResultPanel.ResultPanelType.Lose);
                }
            }
        }

        public void ShowResult(bool isWin)
        {
            guidePanel.Hide();
            if (StaticData.curBattleData.battleType == BattleType.RUSH)
            {
                resultPanel.ShowResult(BattleResultPanel.ResultPanelType.Unknown);
            }
            else
            {
                if (isWin)
                {
                    resultPanel.ShowResult(BattleResultPanel.ResultPanelType.Win);
                }
                else
                {
                    resultPanel.ShowResult(BattleResultPanel.ResultPanelType.Lose);
                }
            }
            foreach (var item in heroItems)
            {
                Destroy(item.gameObject);
            }
            heroItems.Clear();

            topObj.SetActive(false);
            bottomObj.SetActive(false);

            roundEffect.Hide();
            comboKit.Hide();
            transferPanel.Hide();
            LeaveAuto();
        }

        public void ShowRoundEffect(int index)
        {
            roundEffect.ShowRound(index);
        }
        public void ShowRoundEffectOver()
        {

        }



        public void ShowTransferPanel()
        {
            if (viewCtrl.curRunningCamp != BattleCamp.Attacker)
            {
                return;
            }
            if (viewCtrl.changeFormationEffect != null)
            {
                viewCtrl.changeFormationEffect.SetActive(true);
            }
            bottomObj.SetActive(false);
            transferPanel.Show();
            autoTimeLeft.Hide();

        }

        public void HideTransferPanel()
        {
            if (viewCtrl.changeFormationEffect != null)
            {
                viewCtrl.changeFormationEffect.SetActive(false);
            }
            bottomObj.SetActive(true);
            //transBtn.SetActive(false);
            HideChangeBtn();
            //disTransBtn.SetActive(true);
            transferPanel.Hide();
        }

        public void ShowComboNumber(int number)
        {
            comboKit.ShowComboNumber(number);
          
        }

        public void OnSkillBtnClick(string heroUid, int skillType)
        {
            if (skillType == (int)SkillType.Ultimate)
            {
                if (BattleViewCtrl.GetInstance().isUltimateBeginCast)
                {
                    return;
                }
                else
                {
                    BattleViewCtrl.GetInstance().isUltimateBeginCast = true;
                }
            }
            CSSkillCast msg = new CSSkillCast();
            msg.actorUid = heroUid;
            msg.camp = (int)BattleCamp.Attacker;
            msg.skillType = skillType;
            BattleViewCtrl.GetInstance().AskSkillCast(msg);

            if (StaticData.curBattleData.battleType == BattleType.FIRST)
            {
                var ctrl = viewCtrl as BattleViewFirstCtrl;
                if (ctrl.curGuideStep == BattleViewFirstCtrl.FirstBattleGuideStep.NormalSkillNeedSecondCast)
                {
                    Time.timeScale = 1f;
                    BattleManager.Instance.battlePanel.guidePanel.Hide();
                    ctrl.curGuideStep = BattleViewFirstCtrl.FirstBattleGuideStep.NormalSkillSecondCasting;
                    FirstCheckPointUtil.CheckPoint(EnterGameCheckPointEnum.GuideSecondSkill);
                    BattleManager.Instance.battlePanel.guidePanel.Show(null, ctrl.curGuideStep);
                }
            }
        }

        public void ReceiveSkillCastMessage(string heroUid, SkillType skillType)
        {
            transBtn.SetActive(false);
            //disTransBtn.SetActive(true);
            var bhi = GetItemByUid(heroUid);
            if (bhi != null)
            {
                HideCooldown();
                HideAutoCountDownLabel();
                bhi.CastSkill(skillType);
            }
        }

        public BattleHeroItem GetItemByUid(string heroUid)
        {
            for (int i = 0; i < heroItems.Count; ++i)
            {
                if (heroItems[i].uniqueId == heroUid)
                {
                    return heroItems[i];
                }
            }
            return null;
        }
        private int oldNumber = -1;
        public void Update()
        {
            int num = 0;
            if (viewCtrl.curRunningCamp == BattleCamp.Attacker)
            {
                num = (int)(viewCtrl.GetAngerNum(BattleCamp.Attacker) / viewCtrl.GetAngerMax(BattleCamp.Attacker) * 3f);
            }
            if (oldNumber != num)
            {
                oldNumber = num;
            }

            switch (num)
            {
                case 0:
                    angerEffect1.SetActive(false);
                    angerEffect2.SetActive(false);
                    angerEffect3.SetActive(false);
                    angerMark1.SetActive(false);
                    angerMark2.SetActive(false);
                    angerMark3.SetActive(false);
                    break;
                case 1:
                    angerEffect1.SetActive(true);
                    angerEffect2.SetActive(false);
                    angerEffect3.SetActive(false);
                    angerMark1.SetActive(false);
                    angerMark2.SetActive(false);
                    angerMark3.SetActive(false);
                    break;
                case 2:
                    angerEffect1.SetActive(false);
                    angerEffect2.SetActive(true);
                    angerEffect3.SetActive(false);
                    angerMark1.SetActive(false);
                    angerMark2.SetActive(false);
                    angerMark3.SetActive(false);
                    break;
                case 3:
                    angerEffect1.SetActive(false);
                    angerEffect2.SetActive(false);
                    angerEffect3.SetActive(true);
                    angerMark1.SetActive(false);
                    angerMark2.SetActive(false);
                    angerMark3.SetActive(false);
                    break;
            }
            angerBar.SetValue(viewCtrl.GetAngerNum(BattleCamp.Attacker), viewCtrl.GetAngerMax(BattleCamp.Attacker));
        }


        public void BeginTrans()
        {
            viewCtrl.BeginTrans();
        }

        public void TransRight()
        {
            viewCtrl.SendTransfer(false);
        }

        public void TransLeft()
        {
            viewCtrl.SendTransfer(true);
        }

        public void TransConfirm()
        {
            viewCtrl.SendConfirmTrans();
        }

        public void OnResultClick()
        {
            if (StaticData.isTestBattle)
            {
                ManagerController.Instance.BattleToRoom();
                UI.PageManager.Instance.currentPage.Close();
                Room.RoomManager.Switch(SceneType.TOWN);
                return;
            }

            resultPanel.OnResultPanelClick();

        }

        public Transform ultiPaintTransform;
        public GameObject ultiPaintMask;

        public void ShowUltimatePaint(string paintResUrl)
        {
#if !FIX_RESOURCE
            var _obj = AssetLoad.AssetBundleManager.Instance.GetAssetFromBundle(paintResUrl, CommonMethod.GetAssetNameFromAssetBundleName(paintResUrl), typeof(GameObject)) as GameObject;
#else
            var _obj = AssetLoad.ResourceManager.Instance.GetResource(paintResUrl) as GameObject;
#endif
            if (_obj != null)
            {
                var obj = GameObject.Instantiate(_obj) as GameObject;
                MotionBlurControl mbc = obj.GetComponentInChildren<MotionBlurControl>();
                if(mbc != null)
                {
                    obj.transform.SetParent(ultiPaintTransform);
                    obj.transform.localPosition = Vector3.zero;
                    obj.transform.localEulerAngles = Vector3.zero;
                    obj.transform.localScale = Vector3.one;
                    mbc.motionBlur = UICamera.currentCamera.GetComponent<UnityStandardAssets.ImageEffects.MotionBlur>();
                    obj.SetActive(true);
                    curUltimatePaint = obj;
                    UICamera.currentCamera.GetComponent<UnityStandardAssets.ImageEffects.MotionBlur>().enabled = true;
                }
                else
                {
                    return;
                }
            }
            ultiPaintMask.SetActive(true);
            ultiPaintMask.GetComponent<UITweener>().ResetToBeginning();
            ultiPaintMask.GetComponent<UITweener>().PlayForward();
        }

        GameObject curUltimatePaint = null;
        public void HideUltimatePaint()
        {
            if (curUltimatePaint != null)
            {
                GameObject.Destroy(curUltimatePaint);
                curUltimatePaint = null;
                UICamera.currentCamera.GetComponent<UnityStandardAssets.ImageEffects.MotionBlur>().enabled = false;
            }
            ultiPaintMask.SetActive(false);
        }

        public void ShowCooldown(float time)
        {
            cooldownKit.Show(time);
        }
        public void HideCooldown()
        {
            cooldownKit.Hide();
        }

        public GameObject pausePanel;

        public void OnPauseClick()
        {
            if (BattleManager.Instance.isPause)
            {
                Time.timeScale = 1f;
                pausePanel.SetActive(false);
            }
            else
            {
                Time.timeScale = 0f;
                pausePanel.SetActive(true);
            }
            BattleManager.Instance.isPause = !BattleManager.Instance.isPause;
        }

        public void OnExitClick()
        {
            pausePanel.SetActive(false);
            gameObject.SetActive(false);
            BattleManager.Instance.battleViewCtrl.gameObject.SetActive(false);
            //Copy.CopyManager.Instance.BattleToCopy();
            Time.timeScale = 1f;
        }

        public GameObject autoButton;

        public void OnAutoButtonClick()
        {
            if (StaticData.curBattleData.battleType == BattleType.PVP ||
                StaticData.curBattleData.battleType == BattleType.PLUNDER ||
                StaticData.curBattleData.battleType == BattleType.FIELD_PVP)
                return;
            BattleViewCtrl.GetInstance().SendAuto(!BattleViewCtrl.GetInstance().isAuto);
        }

        public void OnSkilButtonClick()
        {
            if (StaticData.curBattleData.battleType == BattleType.PVE ||
                StaticData.curBattleData.battleType == BattleType.FIELD_PVE ||
                StaticData.curBattleData.battleType == BattleType.FIELD_BOSS)
            {
                int level = Dict.Blo.DictConfigBlo.GetSkipBattleLimitLevel();
                int vipLevel = Dict.Blo.DictConfigBlo.GetSkipBattleLimitVIPLevel();
                if (StaticData.playerData.level >= level || StaticData.playerData.vip >= vipLevel)
                {
                    BattleManager.Instance.Skip();
                }
                else
                {
                    var str = string.Format(TableTextBlo.GetText("skip_battle_limit_text"), level, vipLevel);
                    BoxManager.CreatePopupTextBox(str);
                }
            }
            else
            {
                BattleManager.Instance.Skip();
            }
        }

        public enum AutoType
        {
            Auto,
            UnAuto,
            NextRoundAuto,
            NextRoundUnAuto
        }

        public AutoType autoType;
        public void EnterAuto()
        {
            autoType = AutoType.Auto;
            notTurnMask.SetActive(true);
            autoButton.GetComponent<UISprite>().spriteName = "UI_button_zidong_c";
            autoButton.GetComponent<UISprite>().MakePixelPerfect();
            HideAutoCountDownLabel();
            if (StaticData.curBattleData.battleType != BattleType.FIRST)
            {
                speedButton.SetActive(true);
                speedButton.GetComponent<SpeedBtn>().Refresh();
                autoSkipUltiButton.SetActive(true);
                autoSkipUltiButton.GetComponent<SkipUltiBtn>().Refresh();
            }
            else
            {
                speedButton.SetActive(false);
                autoSkipUltiButton.SetActive(false);
            }
        }

        public void LeaveAuto()
        {
            autoType = AutoType.UnAuto;
            autoButton.GetComponent<UISprite>().spriteName = "UI_button_zidong_a";
            autoButton.GetComponent<UISprite>().MakePixelPerfect();
            notTurnMask.SetActive(false);
            HideAutoCountDownLabel();
            if (StaticData.curBattleData.battleType != BattleType.FIRST)
            {
                speedButton.SetActive(false);
                speedButton.GetComponent<SpeedBtn>().Refresh();
                autoSkipUltiButton.SetActive(false);
            }
            else
            {
                speedButton.SetActive(false);
                autoSkipUltiButton.SetActive(false);
            }
        }



        public GameObject GetBattleHeroItem(string uid)
        {
            foreach (var heroItem in heroItems)
            {
                if (heroItem.owner.uniqueId == uid)
                    return heroItem.gameObject;
            }
            return null;

        }

        public void EnterComboGuide(OnComboGuideEnd onEnd)
        {
            guidePanel.GetComponent<ComboGuidePanel>().onEnd = onEnd;
            guidePanel.GetComponent<ComboGuidePanel>().Play();
        }


        List<BCUIParticleTransform> uiParticleTrans = new List<BCUIParticleTransform>();

        public BCUIParticleTransform GetBCUIParticleTransform(BattleCharacter bc, string bind)
        {
            foreach (var p in uiParticleTrans)
            {
                if (p.ownBC.uniqueId == bc.uniqueId && p.bindBoneName == bind)
                {
                    return p;
                }
            }

            GameObject trans = new GameObject(bc.uniqueId + "-" + bind);
            trans.transform.SetParent(buffAnchor);
            var tr = trans.AddComponent<BCUIParticleTransform>();
            tr.Init(bc, bind);
            uiParticleTrans.Add(tr);
            return tr;
        }

    }
}